import React, { Component } from 'react';
import WithRouter from 'react-router';
import { Icon, Input, Button, Table, Popconfirm, message, Form } from 'antd';
import AddForm from './AddForm';
import EditForm from './EditForm';
import axios from 'axios';
import qs from 'qs';
import './index.less';
const Search = Input.Search;


class home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      infor: {}
    };
  }
  columns = [{
    title: '序号',
    dataIndex: 'id',
    key: 'id',
    sorter: (a, b) => a.id - b.id,
  }, {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
  }, {
    title: '账户',
    dataIndex: 'username',
    key: 'username',
  }, {
    title: '性别',
    dataIndex: 'sex',
    key: 'sex',
  }, {
    title: '备注',
    dataIndex: 'description',
    key: 'description',
  }, {
    title: '更新时间',
    dataIndex: 'updTime',
    key: 'updTime',
  }, {
    title: '最后更新人',
    dataIndex: 'updName',
    key: 'updName',
  }, {
    title: '操作',
    key: '操作',
    render: (text, record) => (
      <span>
        <Button type="primary" size="small" onClick={() => this.showEditForm(record)} >编辑</Button>
        {/* <Button type="danger" size="small" onClick={()=>this.deleteUser(record.id)}>删除</Button> */}
        <Popconfirm title="此操作将永久删除, 是否继续?" okText="确认" cancelText="取消" onConfirm={() => this.deleteUser(record.id)}>
          <Button type="danger" size="small" >删除</Button>
        </Popconfirm>
      </span>
    ),
  }];

  // 查询所有用户展出
  getUser = () => {
    const $this = this;
    const Token = sessionStorage.getItem('token');
    axios({
      method: 'get',
      url: '/api/admin/user/all',
      headers: {
        Authorization: Token
      }
    }).then(function (response) {
      if (response.data.legth != 0 && response.data.status != 40301) {
        $this.setState({
          data: response.data
        });
      }
    }).catch(function (error) {
      message.error('请求失败，请稍后重试');
    });

  }
  // 条件搜索
  searchUser = (value) => {
    const $this = this;
    const Token = sessionStorage.getItem('token');
    axios({
      method: 'get',
      url: '/api/admin/user',
      headers: {
        Authorization: Token
      },
      params: {
        name: value
      }
    }).then(function (response) {
      $this.setState({
        data: response.data
      });
    }).catch(function (error) {
      message.error('请求失败，请稍后重试');
    });

  }
  showAddForm = () => { this.setState({ addFormVisible: true, }) }
  hideAddForm = () => { this.setState({ addFormVisible: false, }) }
  showEditForm = (a) => {
    // console.log(a)
    this.setState({ editFormVisible: true, infor: a });
  }
  hideEditForm = (a) => { this.setState({ infor: a, editFormVisible: false }) }

  // 添加用户
  handleCreate = (_this) => {
    // console.log(b)
    _this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log(_this);
        const $this = this;
        const Token = sessionStorage.getItem('token');
        axios({
          method: 'post',
          url: '/api/admin/user/register',
          headers: {
            Authorization: Token
          },
          data: values
        })
          .then(function (response) {
            if (response.data.data) {
              message.error(response.data.data);

            } else {
              $this.setState({ addFormVisible: false });
              message.success('添加成功');
              $this.getUser();
            }

          })
          .catch(function (error) {
            message.error('请求失败，请稍后重试');
          });
      }
    });
  }
  // 删除用户
  deleteUser = (id) => {
    const $this = this;
    const Token = sessionStorage.getItem('token');
    axios({
      method: 'delete',
      url: '/api/admin/user/' + id,
      headers: {
        Authorization: Token
      }
    }).then(function (response) {
      message.success('删除成功');
      $this.getUser();
    }).catch(function (error) {
      message.error('请求失败，请稍后重试');
    });
  }
  // 编辑用户
  EditUser = (Value) => {
    const $this = this;
    if ($this.state.infor.id != undefined) {

      const Token = sessionStorage.getItem('token');
      const dataValues = Value;
      dataValues.id = $this.state.infor.id;
      axios({
        method: 'put',
        url: '/api/admin/user/' + $this.state.infor.id,
        headers: {
          Authorization: Token
        },
        data: dataValues,
      }).then(function (response) {
        console.log(response);
        message.success('更新成功');
        $this.getUser();
      }).catch(function (error) {
        message.error('请求失败，请稍后重试');
      });
    }
    // })
    // form.resetFields();
    this.setState({ editFormVisible: false });
  }
  // saveFormRef = (formRef) => {
  // this.formRef1 = formRef;
  // }
  // saveFormRef2 = (formRef) => {
  // this.formRef2 = formRef;
  // }
  componentWillMount() {
    this.getUser();
  }
  render() {


    return (
      <div>
        <div className="index-buttons">
          <Search placeholder="姓名或账户" onSearch={value => this.searchUser(value)} enterButton size="large" style={{ width: 260 }} />
          <Button type="primary" size="large" icon="edit" onClick={this.showAddForm}>添加</Button>
        </div>
        <Table columns={this.columns} dataSource={this.state.data} rowKey="id" bordered />
        {/* 如果你的数据没有这个属性，务必使用 rowKey 来指定数据列的主键。若没有指定，控制台会出现以下的提示，表格组件也会出现各类奇怪的错误。 */}
        <AddForm
          // wrappedComponentRef={this.saveFormRef}
          visible={this.state.addFormVisible}
          onCancel={this.hideAddForm}
          onCreate={this.handleCreate}
        />
        {
          this.state.infor ? <EditForm
            // wrappedComponentRef={this.saveFormRef2}
            visible={this.state.editFormVisible}
            infor={this.state.infor}
            onCancel={() => this.hideEditForm('')}
            onCreate={this.EditUser}

          />
          : ''
        }
      </div>


    );
  }
}
const Home = Form.create()(home);
export default Home;
